﻿using DocBot.Objects;
using DocBot.Util;
using DocBot.Util.Collections;

using GalaSoft.MvvmLight;

using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;

namespace DocBot.ViewModel
{
	public class AudioDeviceViewModel : ViewModelBase, INotifyPropertyChanged
	{
		#region Members
		ThreadSafeObservableCollection<AudioDevice> _audiodevices = new ThreadSafeObservableCollection<AudioDevice>();
		int _selectedAudioDevice = -1;
		#endregion

		#region Properties
		public ThreadSafeObservableCollection<AudioDevice> AudioDevices
		{
			get
			{
				return _audiodevices;
			}
			set
			{
				_audiodevices = value;
			}
		}

		public int SelectedAudioDevice
		{
			get
			{
				return this._selectedAudioDevice;
			}
			set
			{
				if (value != this._selectedAudioDevice)
				{
					this._selectedAudioDevice = value;
					NotifyPropertyChanged();
				}
			}
		}
		#endregion

		#region Events
		new virtual public event PropertyChangedEventHandler PropertyChanged;

		// This method is called by the Set accessor of each property.
		// The CallerMemberName attribute that is applied to the optional propertyName
		// parameter causes the property name of the caller to be substituted as an argument.
		private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
				if (propertyName == "SelectedAudioDevice")
				{
					Settings.Instance.VLC_MediaPlayerWaveOutDevice = _audiodevices[SelectedAudioDevice].Name;
				}
			}
		}
		#endregion

		#region Construction
		public AudioDeviceViewModel()
		{
			if (_audiodevices == null)
				return;
			WaveDevices.WAVEOUTCAPS[] _devices = WaveDevices.GetDevCapsPlayback();
			for (int i = 0; i < _devices.Count(); i++)
			{
				_audiodevices.Add(new AudioDevice { Name = _devices[i].ToString() });
				if (_devices[i].ToString() == Settings.Instance.VLC_MediaPlayerWaveOutDevice)
					SelectedAudioDevice = i;
			}
		}
		#endregion
	}
}
